package com.monkeygroup.mygoplus.view.home.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import android.util.Log;


import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.common.imageview.DirsPopWindow;
import com.monkeygroup.mygoplus.common.imageview.FolderModel;
import com.monkeygroup.mygoplus.common.imageview.ImageAdapter;
import com.monkeygroup.mygoplus.common.utils.ImageTools;
import com.monkeygroup.mygoplus.common.utils.LocalInfo;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.common.utils.YFileManager;
import com.monkeygroup.mygoplus.common.utils.YTools;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.thing.vo.MyImageVO;
import com.monkeygroup.mygoplus.user.vo.PersonalNomalInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;

/**
 * Created by cumt on 2017/6/2.
 */

public class ImageActivity extends BaseActivity implements View.OnClickListener {

    public static void gotoActivity(Activity activity, String type) {
        Intent intent = new Intent(activity,
                ImageActivity.class);
        //1-,2-头像，3-背景图
        intent.putExtra("type", type);
        activity.startActivityForResult(intent, 1);
    }

    private Activity activity;
    private ImageView imgBack;
    private TextView txtTitle, txt_top;

    private GridView imageGrid;
    private TextView dirName;
    private TextView dirCount;
    private ProgressDialog progressDialog; // 加载图片时出现的加载对话框
    private DirsPopWindow popWindow; // 可弹出的目录菜单
    private RelativeLayout bottomLayout;

    private List<String> imageList; // 图片的数据集
    private File currentDir; // 当前所在的文件目录
    private int totalCount; // 显示dirCount中的数据
    private List<FolderModel> folderModels = new ArrayList<FolderModel>();
    private ImageAdapter imageAdapter;

    private static final int DATA_LOADED = 0x110;

    StringBuffer height, width, size, name;

    //請求參數
    private Map<String, String> params = new HashMap<>();
    ;
    private HttpModel httpModel;
    private HttpModel upload;
    private StringBuffer url;
    private String type;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == DATA_LOADED) {
                progressDialog.dismiss();
                bindDataToView();

                initDirsPopWindow();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void setContentView() {
        setContentView(R.layout.sideworks_image);


    }

    /**
     * 初始化弹出菜单
     */
    private void initDirsPopWindow() {
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                lightOn();
            }
        });
    }

    /**
     * 弹出窗口消失之后，需要将后面的图片列表变亮
     */
    private void lightOn() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f;
        getWindow().setAttributes(lp);
    }

    /**
     * 在现实PopUpWindow之后将后面的图片列表置黑
     */
    private void lightOff() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);
    }

    /**
     * 绑定数据到View中
     */
    private void bindDataToView() {
        if (currentDir == null) {
            Toast.makeText(ImageActivity.this, "未扫描到任何图片！", Toast.LENGTH_SHORT).show();
            return;
        }
        imageList = Arrays.asList(currentDir.list());
        imageAdapter = new ImageAdapter(ImageActivity.this, imageList, currentDir.getAbsolutePath(), type);
        imageGrid.setAdapter(imageAdapter);

        dirCount.setText(totalCount + "");
        dirName.setText(currentDir.getName());
    }

    /**
     * 初始化数据（利用ContentProvider扫描手机中的所有图片）
     */
    @SuppressLint("NewApi")
    private void initData() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(ImageActivity.this, "当前存储卡不可用！", Toast.LENGTH_SHORT).show();
            return;
        }
        progressDialog = ProgressDialog.show(ImageActivity.this, null, "正在加载...");

        //询问权限
        int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
            Activity activty = ImageActivity.this;
            //
            ActivityCompat.requestPermissions(activty, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);

            return;
        } else {
            startGetImageThread();
        }
    }


    /**
     * 初始化控件
     */
    @Override
    public void initView() {

        activity = ImageActivity.this;
        imgBack = (ImageView) findViewById(R.id.img_back);
        txtTitle = (TextView) findViewById(R.id.txt_title);
        txt_top = (TextView) findViewById(R.id.txt_top);
        txt_top.setText("上傳");

        imageGrid = (GridView) findViewById(R.id.find_main_gv_images);
        dirName = (TextView) findViewById(R.id.find_main_tv_toall);
        dirCount = (TextView) findViewById(R.id.find_main_tv_num);
        bottomLayout = (RelativeLayout) findViewById(R.id.find_main_rl_bottomlayout);
        popWindow = new DirsPopWindow(ImageActivity.this, folderModels);


        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        type = bundle.getString("type");

        initData();
    }

    @Override
    public void setListener() {


        txt_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();

                int count = 0;
                Set<String> set = imageAdapter.selectedImages;
                StringBuffer selectedImages = new StringBuffer("");
                StringBuffer selectedImagesUrl = new StringBuffer("");


                Iterator<String> it = set.iterator();
                height = new StringBuffer("");
                width = new StringBuffer("");
                size = new StringBuffer("");
                name = new StringBuffer("");
                List<File> imgs = new ArrayList<File>();
                while (it.hasNext()) {
                    String str = it.next();
                    Log.e("strstrs====", "" + str);
                    selectedImages.append(str);
                    selectedImages.append(",");

                    try {
                        File toFile = YFileManager.getLeaveMsgPicsCacheFile(System
                                .currentTimeMillis() + "_small.jpg");
                        File source = new File(str);


                        BitmapFactory.Options options = new BitmapFactory.Options();

                        /**
                         * 最关键在此，把options.inJustDecodeBounds = true;
                         * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
                         */
                        options.inJustDecodeBounds = true;
                        Bitmap bitmap = BitmapFactory.decodeFile(str, options); // 此时返回的bitmap为null

                        height.append("" + options.outHeight);
                        height.append(",");

                        width.append("" + options.outWidth);
                        width.append(",");
                        Log.e("options.outWidth===", "" + options.outWidth);
                        size.append("" + source.length());
                        size.append(",");

                        name.append("" + source.getName());
                        name.append(",");


                        if (ImageTools.zoomPic(activity, source, toFile)) {
                            imgs.add(toFile);
                        } else {

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(activity, "存储卡空间不足或者无法读写手机存储卡",
                                Toast.LENGTH_SHORT).show();

                    }
                    //     File source = YTools.getImageFromSys(activity, str);
                    //   imgs.add(str);
//                    fillFile(str,count);
                }
                String img = fillFile(intent, imgs, count);
                //                    selectedImagesUrl.append(",");
//                    selectedImagesUrl.append(img);
//                intent.putExtra("selectedImagesUrl",selectedImagesUrl.toString());


            }
        });
    }

    @Override
    public void doEvent() {
//        bottomLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                popWindow.setAnimationStyle(R.style.Style_PopWindow_Anim);
//                popWindow.showAsDropDown(bottomLayout,0 ,0 );
//                lightOff();
//            }
//        });

        txtTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.setAnimationStyle(R.style.Style_PopWindow_Anim);
                popWindow.showAsDropDown(txtTitle, 0, 0);
                lightOff();
            }
        });


        popWindow.setOnDirSelectListener(new DirsPopWindow.OnDirSelectListener() {
            @Override
            public void onDirSelected(FolderModel folder) {
                currentDir = new File(folder.getDir());
                imageList = Arrays.asList(currentDir.list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png")) {
                            return true;
                        }
                        return false;
                    }
                }));
                imageAdapter = new ImageAdapter(ImageActivity.this, imageList, currentDir.getAbsolutePath(), type);


                imageGrid.setAdapter(imageAdapter);
                dirCount.setText(imageList.size() + "");
                dirName.setText(folder.getName());

                popWindow.dismiss();
            }
        });
    }

    private String fillFile(final Intent intent, final List<File> filePath, int count) {
        params.clear();
        PersonalNomalInfo user = LocalInfo.getUserInfo(ImageActivity.this);
        final StringBuffer selectedImagesUrl = new StringBuffer("");

        params.put("mobile", user.getMobile());
//        List<File> files = null;
////        File file = null;
//        try {
//             files = new ArrayList<>();
//            for(int i=0 ;i<filePath.size();i++){
//               File  file = new File(filePath.get(i));
//                files.add(file);
//            }
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        Log.e("filePathfilePath==", "" + filePath);

        if ("1".equals(type)) {
            url = new StringBuffer(RequestUrl.baseUrl + RequestUrl.uploadImg);
        } else if ("2".equals(type)) {
            url = new StringBuffer(RequestUrl.baseUrl + RequestUrl.uploadPortraitImg);
        } else if ("3".equals(type)) {
            url = new StringBuffer(RequestUrl.baseUrl + RequestUrl.uploadBackgroundImg);
        }

        for (int i = 0; i < filePath.size(); i++) {

            //上傳圖片請求
            HttpModel upload = new HttpModel(url.toString(), params, new HttpModel.SimpleOnHttpRequestListener() {
                @Override
                public void onRequestFinished(int resultCode, String resultMsg, Object data) {
//                if(VilidateUtil.isSuccess(resultCode)){
//                    Log.e("上傳圖片=====", resultMsg+"==="+((Map)data).get("path"));

                    Map map = ((Map) data);
                    Log.e("datadata==", "" + map.get("path"));
                    selectedImagesUrl.append(map.get("path"));
                    selectedImagesUrl.append(",");
                    Log.e("siesisee==", "" + selectedImagesUrl.toString().split(",").length);
                    if (selectedImagesUrl.toString().split(",").length == (filePath.size())) {

                        intent.putExtra("selectedImages", selectedImagesUrl.toString());
                        intent.putExtra("type", type);
                        Log.e("widthwidth1===:::", "" + width.toString());
                        intent.putExtra("height", height.toString());
                        intent.putExtra("width", width.toString());
                        intent.putExtra("size", size.toString());
                        intent.putExtra("name", name.toString());
                        Log.e("selectedImage===", selectedImagesUrl.toString());
//                    intent.putExtra("selectedImages", selectedImagesUrl.toString());
                        imageAdapter.selectedImages.clear();
                        ImageActivity.this.setResult(RESULT_OK, intent);
                        finish();
                    }
//                }

                }
            }, "files", filePath.get(i));

            upload.uploadFile();


        }


        return selectedImagesUrl.toString();
    }

    @Override
    protected void onDestroy() {
        progressDialog.dismiss();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 0) {
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //用户同意使用write
                startGetImageThread();
            } else {
                //用户不同意，自行处理即可
                finish();
            }
        }
    }

    private void startGetImageThread() {
        new Thread() {
            @Override
            public void run() {


                /**
                 * 初始化FolderModel，为PopUpWindow做准备
                 */
                Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver cr = ImageActivity.this.getContentResolver();
                Cursor cursor = cr.query(imageUri, null, MediaStore.Images.Media.MIME_TYPE + " = ? or " + MediaStore.Images.Media.MIME_TYPE + " = ? ",
                        new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);
                Set<String> dirPaths = new HashSet<String>();
                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); // 获取图片的路径
                    File parentFile = new File(path).getParentFile(); // 获取该图片所在的父路径名
                    if (parentFile == null) {
                        continue;
                    }
                    String dirPath = parentFile.getAbsolutePath();
                    FolderModel folder = null;
                    // 放置重复扫描
                    if (dirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        dirPaths.add(dirPath);
                        folder = new FolderModel();
                        folder.setDir(dirPath);
                        folder.setFirstImgPath(path);
                    }
                    if (parentFile.list() == null) {
                        continue;
                    }
                    int picSize = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png")) {
                                return true;
                            }
                            return false;
                        }
                    }).length;
                    folder.setCount(picSize);
                    folderModels.add(folder);
                    if (picSize > totalCount) {
                        totalCount = picSize;
                        currentDir = parentFile;
                    }
                }
                cursor.close();
                // 扫描完成，释放临时变量的内存
                dirPaths = null;
                handler.sendEmptyMessage(DATA_LOADED); // 通知Handler扫描图片完成
            }
        }.start();
    }
}
